/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    can.c
  * @brief   This file provides code for the configuration
  *          of the CAN instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "can.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

CAN_HandleTypeDef hcan;

/* CAN init function */
void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN1;
  hcan.Init.Prescaler = 8;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_6TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_2TQ;
  hcan.Init.TimeTriggeredMode = DISABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = DISABLE;
  hcan.Init.AutoRetransmission = ENABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */
  CAN_FilterTypeDef Filter;
   Filter.FilterIdHigh = 0X0000;
   Filter.FilterMaskIdLow = 0X0000;
   Filter.FilterIdLow = 0X0000;
   Filter.FilterMaskIdHigh = 0X0000;
   Filter.FilterMode = CAN_FILTERMODE_IDMASK;
   Filter.FilterScale = CAN_FILTERSCALE_32BIT;
   Filter.FilterActivation = CAN_FILTER_ENABLE;
   Filter.FilterBank = 0;
   Filter.FilterFIFOAssignment = CAN_FILTER_FIFO0;
   Filter.SlaveStartFilterBank = 27;

   if( HAL_CAN_ConfigFilter(&hcan, &Filter)!=HAL_OK)
  {

 	   Error_Handler();

   }
   if( HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING)!=HAL_OK)
   {

   	  Error_Handler();
   }
  /* USER CODE END CAN_Init 2 */

}

void HAL_CAN_MspInit(CAN_HandleTypeDef* canHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspInit 0 */

  /* USER CODE END CAN1_MspInit 0 */
    /* CAN1 clock enable */
    __HAL_RCC_CAN1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* CAN1 interrupt Init */
    HAL_NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspInit 1 */

  /* USER CODE END CAN1_MspInit 1 */
  }
}

void HAL_CAN_MspDeInit(CAN_HandleTypeDef* canHandle)
{

  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspDeInit 0 */

  /* USER CODE END CAN1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_CAN1_CLK_DISABLE();

    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_11|GPIO_PIN_12);

    /* CAN1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspDeInit 1 */

  /* USER CODE END CAN1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
CAN_TxHeaderTypeDef Tx_pHeader;
uint32_t CAN_TX_Message(uint8_t TxData[], uint8_t length)
{

	uint32_t TxMailboxNumber = 0x00000000U;    // 存储本次发�?�所使用邮箱的邮箱号

	Tx_pHeader.StdId = 0x01;    // 以此ID发�??
	Tx_pHeader.ExtId = 0x0000;    // 扩展ID（此处无用）
	Tx_pHeader.IDE = CAN_ID_STD;    // 标准�??
	Tx_pHeader.RTR = CAN_RTR_DATA;    // 数据�??
	Tx_pHeader.DLC = length;    // 发�?�数据的长度
	Tx_pHeader.TransmitGlobalTime = DISABLE;

	if(HAL_CAN_AddTxMessage(&hcan, &Tx_pHeader, TxData, &TxMailboxNumber) != HAL_OK)
	{
		return Tx_Error;
	}
	return TxMailboxNumber;
}

uint8_t RxData[8] = {0};    // 缓存接收到的信息

CAN_RxHeaderTypeDef Rx_pHeader;
/*
 * @brief: CAN Receive Message.
 * @param: "RxData[]" will store the message which has been received, which length must between 0 and 8.
 * @retval: receive status.
 */
uint32_t CAN_RX_Message(uint8_t RxData[])
{

	uint8_t aData[8];    // 缓存接收到的信息

	Rx_pHeader.StdId = 0x000;	// 接收ID（此处无用，can接收�??有的ID号）
	Rx_pHeader.ExtId = 0x0000;
	Rx_pHeader.IDE = CAN_ID_STD;	// 接收标准�??
	Rx_pHeader.DLC = 8;		// 接收8�??8bit数据
	Rx_pHeader.RTR = CAN_RTR_DATA;	// 接收数据�??
	Rx_pHeader.FilterMatchIndex = 0;	// 使用0号过滤器
	Rx_pHeader.Timestamp = 0;

	if(HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &Rx_pHeader, aData) != HAL_OK)
	{
		return Rx_Error;
	}
	else
	{
		// 取出接收到的信息
		for(uint8_t i = 0; i<Rx_pHeader.DLC; i++)
		{
			RxData[i] = aData[i];
		}
		return Rx_OK;
	}
}

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
    // 判断是哪�??路的CAN发生了中�??
	if(hcan->Instance == CAN1)
	{
		if(CAN_RX_Message(RxData) != Rx_OK)
		{
            // 接收信息失败
			printf("MCU Received CAN Data ERROR!!!");
            printf("\n\r");
			printf("\n\r");
		}
		else
		{
            // 接受信息成功，处理数�??
			 // HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_RESET);
			CAN_TX_Message(RxData,8);
		}
	}
}
/* USER CODE END 1 */
